package com.demo.controller;

import com.demo.common.Result;
import com.demo.pojo.dto.AdvancedScheduleRequestDTO;
import com.demo.pojo.entity.Clazz;
import com.demo.pojo.entity.Course;
import com.demo.service.impl.AdvancedScheduleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 高级智能排课控制器
 */
@RestController
@RequestMapping("/advanced-schedule")
@CrossOrigin
public class AdvancedScheduleController {
    
    @Autowired
    private AdvancedScheduleServiceImpl advancedScheduleService;
    
    /**
     * 执行高级智能排课
     */
    @PostMapping("/execute")
    public Result<String> executeAdvancedSchedule(@RequestBody AdvancedScheduleRequestDTO request) {
        try {
            System.out.println("收到高级智能排课请求：" + request);
            
            // 参数验证
            if (request.getSemester() == null || request.getSemester().trim().isEmpty()) {
                return Result.error("学期不能为空");
            }
            
            if (request.getMaxPeriodsPerWeek() == null || request.getMaxPeriodsPerWeek() <= 0) {
                request.setMaxPeriodsPerWeek(12); // 默认值
            }
            
            if (request.getMaxPeriodsPerDay() == null || request.getMaxPeriodsPerDay() <= 0) {
                request.setMaxPeriodsPerDay(8); // 默认值
            }
            
            if (request.getEvenDistribution() == null) {
                request.setEvenDistribution(true); // 默认值
            }
            
            if (request.getAvoidTeacherConflict() == null) {
                request.setAvoidTeacherConflict(true); // 默认值
            }
            
            if (request.getAvoidClassroomConflict() == null) {
                request.setAvoidClassroomConflict(true); // 默认值
            }
            
            if (request.getPriority() == null || request.getPriority() < 1 || request.getPriority() > 5) {
                request.setPriority(3); // 默认值
            }
            
            boolean success = advancedScheduleService.executeAdvancedSchedule(request);
            
            if (success) {
                return Result.success("高级智能排课执行成功！\n" +
                    "学期：" + request.getSemester() + "\n" +
                    "选择班级数量：" + (request.getSelectedClazzIds() != null ? request.getSelectedClazzIds().size() : "全部") + "\n" +
                    "选择课程数量：" + (request.getSelectedCourseIds() != null ? request.getSelectedCourseIds().size() : "全部") + "\n" +
                    "每周最大课时：" + request.getMaxPeriodsPerWeek() + "\n" +
                    "每天最大课时：" + request.getMaxPeriodsPerDay() + "\n" +
                    "均匀分配：" + (request.getEvenDistribution() ? "是" : "否") + "\n" +
                    "避免教师冲突：" + (request.getAvoidTeacherConflict() ? "是" : "否") + "\n" +
                    "避免教室冲突：" + (request.getAvoidClassroomConflict() ? "是" : "否"));
            } else {
                return Result.error("高级智能排课执行失败，请检查数据完整性");
            }
            
        } catch (Exception e) {
            System.err.println("高级智能排课执行异常：" + e.getMessage());
            e.printStackTrace();
            return Result.error("高级智能排课执行异常：" + e.getMessage());
        }
    }
    
    /**
     * 获取可选择的班级列表
     */
    @GetMapping("/available-clazzes")
    public Result<List<Clazz>> getAvailableClazzes() {
        try {
            List<Clazz> clazzes = advancedScheduleService.getAvailableClazzes();
            return Result.success(clazzes);
        } catch (Exception e) {
            return Result.error("获取班级列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取可选择的课程列表
     */
    @GetMapping("/available-courses")
    public Result<List<Course>> getAvailableCourses() {
        try {
            List<Course> courses = advancedScheduleService.getAvailableCourses();
            return Result.success(courses);
        } catch (Exception e) {
            return Result.error("获取课程列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取默认排课参数
     */
    @GetMapping("/default-params")
    public Result<AdvancedScheduleRequestDTO> getDefaultParams() {
        try {
            AdvancedScheduleRequestDTO defaultParams = new AdvancedScheduleRequestDTO();
            defaultParams.setSemester("advanced");
            defaultParams.setMaxPeriodsPerWeek(12);
            defaultParams.setMaxPeriodsPerDay(8);
            defaultParams.setEvenDistribution(true);
            defaultParams.setAvoidTeacherConflict(true);
            defaultParams.setAvoidClassroomConflict(true);
            defaultParams.setPriority(3);
            defaultParams.setRemark("高级智能排课");
            
            return Result.success(defaultParams);
        } catch (Exception e) {
            return Result.error("获取默认参数失败：" + e.getMessage());
        }
    }
    
    /**
     * 验证排课参数
     */
    @PostMapping("/validate-params")
    public Result<String> validateParams(@RequestBody AdvancedScheduleRequestDTO request) {
        try {
            StringBuilder validation = new StringBuilder();
            validation.append("参数验证结果：\n");
            
            // 验证学期
            if (request.getSemester() == null || request.getSemester().trim().isEmpty()) {
                validation.append("❌ 学期不能为空\n");
            } else {
                validation.append("✅ 学期：").append(request.getSemester()).append("\n");
            }
            
            // 验证课时限制
            if (request.getMaxPeriodsPerWeek() != null && request.getMaxPeriodsPerWeek() > 0) {
                validation.append("✅ 每周最大课时：").append(request.getMaxPeriodsPerWeek()).append("\n");
            } else {
                validation.append("⚠️ 每周最大课时使用默认值：12\n");
            }
            
            if (request.getMaxPeriodsPerDay() != null && request.getMaxPeriodsPerDay() > 0) {
                validation.append("✅ 每天最大课时：").append(request.getMaxPeriodsPerDay()).append("\n");
            } else {
                validation.append("⚠️ 每天最大课时使用默认值：8\n");
            }
            
            // 验证班级选择
            if (request.getSelectedClazzIds() != null && !request.getSelectedClazzIds().isEmpty()) {
                validation.append("✅ 选择班级数量：").append(request.getSelectedClazzIds().size()).append("\n");
            } else {
                validation.append("ℹ️ 将使用所有可用班级\n");
            }
            
            // 验证课程选择
            if (request.getSelectedCourseIds() != null && !request.getSelectedCourseIds().isEmpty()) {
                validation.append("✅ 选择课程数量：").append(request.getSelectedCourseIds().size()).append("\n");
            } else {
                validation.append("ℹ️ 将使用所有有教师的课程\n");
            }
            
            // 验证冲突避免设置
            validation.append("✅ 均匀分配：").append(request.getEvenDistribution() != null && request.getEvenDistribution() ? "是" : "否").append("\n");
            validation.append("✅ 避免教师冲突：").append(request.getAvoidTeacherConflict() != null && request.getAvoidTeacherConflict() ? "是" : "否").append("\n");
            validation.append("✅ 避免教室冲突：").append(request.getAvoidClassroomConflict() != null && request.getAvoidClassroomConflict() ? "是" : "否").append("\n");
            
            return Result.success(validation.toString());
            
        } catch (Exception e) {
            return Result.error("参数验证失败：" + e.getMessage());
        }
    }
}



